package org.liang.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 字符串处理工具.<br>
 * 
 * @author L.Yang
 * @version 2015年11月11日
 * @see StringUtils
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

    /**
     * 判断对象是否为空，为空返回true.
     * 
     * <pre>
     * 为空的条件:
     * 1、null
     * 2、去除前后空格并且不区分大小写(""、"null"、'null')
     * </pre>
     * 
     * @param obj
     *            对象
     * @return 是否为空
     */
    public static final boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        String str = obj.toString().trim();
        if ("".equals(str) || "null".equalsIgnoreCase(str) || "'null'".equalsIgnoreCase(str)) {
            return true;
        }
        return false;
    }

    /**
     * 将驼峰风格替换为下划线风格.
     * 
     * @param str
     *            驼峰风格
     * @return 下划线风格
     */
    public static String camelhumpToUnderline(final String str) {
        Matcher matcher = Pattern.compile("[A-Z]").matcher(str);
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() + i, matcher.end() + i,
                            "_" + matcher.group().toLowerCase());
        }
        if (builder.charAt(0) == '_') {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    /**
     * 将下划线风格替换为驼峰风格.
     * 
     * @param str
     *            下划线风格
     * @return 驼峰风格
     */
    public static String underlineToCamelhump(final String str) {
        Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
        StringBuilder builder = new StringBuilder(str);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() - i, matcher.end() - i,
                            matcher.group().substring(1).toUpperCase());
        }
        if (Character.isUpperCase(builder.charAt(0))) {
            builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
        }
        return builder.toString();
    }

}
